var bodyParser = require('body-parser');
var sql = require('../sql');
var sqlServer = require('mssql');


var config = {
    user: 'sa',
    password: 'r3e556sdf96!',
    server: '192.168.1.66', // You can use 'localhost\\instance' to connect to named instance
    database: 'macroserp'
}

var getComments = function(req, res) {
    sql.Comment.findAll({
        'where': {
            'taskid': req.body.taskid
        },
        'order': 'id desc'
    }).then(function(comments) {
        if (comments) {

            comments = JSON.parse(JSON.stringify(comments))
            for (let i = 0; i < comments.length; i++) {
                sql.File.findAll({
                    'where': {
                        'commentid': comments[i].id
                    }
                }).then(function(files) {
                    comments[i].imgs = files
                })
            }
            sqlServer.connect(config).then(function() {
                for (let i = 0; i < comments.length; i++) {
                    var sqlString = 'select username from scaccount where fidno = ' + comments[i].entuserid;
                    new sqlServer.Request().query(sqlString).then(function(recordset) {
                        // console.log(recordset[0].username);
                        comments[i].entusername = recordset[0].username
                    }).catch(function(err) {
                        // ... query error checks
                    });
                }
                setTimeout(function() {
                    console.log(comments)
                    res.send(comments)
                }, 100)
            })

        } else {
            res.send('无评论')
        }
    })
}
var addComment = function(req, res) {
    sql.Comment.create({
        'fdid': req.body.fdid,
        'content': req.body.content,
        'taskid': req.body.taskid,
        'entuserid': req.body.entuserid
    }).then(function(comment) {
        res.send(comment)
    })
}

var deleteComment = function(req, res) {
    sql.Comment.destroy({
        'where': {
            'id': req.body.id
        }
    }).then(function(comment) {
        if (comment) {
            res.send('删除成功')
            sql.Comment.destroy({
                'where': {
                    'fdid': req.body.id
                }
            })
        } else {
            res.send('无效条目')
        }
    })
}


module.exports = { addComment, deleteComment, getComments }